//
//  MessageDetailVC.m
//  meiang_edu
//
//  Created by Apple on 2018/10/18.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//
#import "MessageDetailVC.h"
#import "MAMessageDetailCell.h"
#import "MAEnteringVC.h"
#import "Toast.h"
#import "AFNetworking.h"
@interface MessageDetailVC ()
<UITableViewDelegate,UITableViewDataSource>
{
    UIView *deleView;//撤销
    UIView *applyView;//报名
}
@property(nonatomic,strong) UIImageView *leftIcon;
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) UIView *headView;
@property(nonatomic,strong) UILabel *titleLabel;
@property(nonatomic,strong) UILabel *senderLabel;
@property(nonatomic,strong) UILabel *contentLabel;
@property(nonatomic,strong) UIImageView *messageImageView;
@property(nonatomic,strong) UILabel *timeLabel;
@property(nonatomic,strong) NSMutableArray *messageArray;
@property(nonatomic,assign) CGFloat  ImageSize;
@property(nonatomic,assign) CGFloat ImageAllSize;
@property(nonatomic,strong)AFHTTPSessionManager *applymanager;
@property(nonatomic,strong)AFHTTPSessionManager *delemanager;
@end

@implementation MessageDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"活动详情";
     [self.leftIcon addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(leftBtnDidClick)]];
    [self.leftIcon setImage:[UIImage imageNamed:@"back"]];
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 7.0, 15, 25.0)];
    [leftView addSubview:self.leftIcon];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftView];
    
    self.tableView=[[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    self.tableView.backgroundColor=[UIColor colorWithRed:0.922 green:0.922 blue:0.922 alpha:1.00];
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.tableView.autoresizingMask=UIViewAutoresizingFlexibleHeight;
    self.tableView.showsVerticalScrollIndicator=NO;
    self.tableView.showsHorizontalScrollIndicator=NO;
    [self.view addSubview:self.tableView];
    
    [self initWithHeadView];
    [self initWithData];
}

#pragma mark 头部view
-(void)initWithHeadView{
    self.headView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 330)];
    self.headView.backgroundColor=[UIColor clearColor];
    self.tableView.tableHeaderView=self.headView;
    
    UIView *bgView=[[UIView alloc] initWithFrame:CGRectMake(6, 6, kScreenWidth-12, 320)];
    bgView.backgroundColor=[UIColor whiteColor];
    bgView.layer.masksToBounds=YES;
    bgView.layer.cornerRadius=10;
    [self.headView addSubview:bgView];
    
    CGFloat width=bgView.frame.size.width;
    //标题
    self.titleLabel=[[UILabel alloc] initWithFrame:CGRectMake(6, 6, width-12, 20)];
    self.titleLabel.textColor=[UIColor colorWithRed:0.200 green:0.200 blue:0.200 alpha:1.00];
    self.titleLabel.font=[UIFont boldSystemFontOfSize:18];
    self.titleLabel.text=@"通知";
    [bgView addSubview:self.titleLabel];
    //发送人
    self.senderLabel=[[UILabel alloc] initWithFrame:CGRectMake(6, CGRectGetMaxY(self.titleLabel.frame)+10, width-12, 20)];
    self.senderLabel.textColor=[UIColor colorWithRed:0.200 green:0.200 blue:0.200 alpha:1.00];
    self.senderLabel.font=[UIFont boldSystemFontOfSize:18];
    self.senderLabel.text=@"发送人：李浩";
    [bgView addSubview:self.senderLabel];
    //内容
    self.contentLabel=[[UILabel alloc] initWithFrame:CGRectMake(6, CGRectGetMaxY(self.senderLabel.frame)+10, width-12, 0)];
    self.contentLabel.textColor=[UIColor colorWithRed:0.200 green:0.200 blue:0.200 alpha:1.00];
    self.contentLabel.font=[UIFont systemFontOfSize:14];
    self.contentLabel.text=@"内容";
    [bgView addSubview:self.contentLabel];
    //图片
    self.messageImageView=[[UIImageView alloc] initWithFrame:CGRectMake(6, CGRectGetMaxY(self.contentLabel.frame)+10, 200, 100)];
    [bgView addSubview:self.messageImageView];
    //时间
    self.timeLabel=[[UILabel alloc] initWithFrame:CGRectMake(6, CGRectGetMaxY(self.messageImageView.frame)+10, width-12, 20)];
    self.timeLabel.textColor=[UIColor colorWithRed:0.608 green:0.608 blue:0.608 alpha:1.00];
    self.timeLabel.font=[UIFont systemFontOfSize:14];
    self.timeLabel.text=@"2018-09-23 10:43";
    [bgView addSubview:self.timeLabel];
    
    applyView=[[UIView alloc] initWithFrame:CGRectMake((kScreenWidth/2.0-60)/2.0, CGRectGetMaxY(self.timeLabel.frame)+10,60, 60)];
    [bgView addSubview:applyView];
    UIImageView *applyImage=[[UIImageView alloc] initWithFrame:CGRectMake(15, 0, 30, 30)];
    [applyImage setImage:[UIImage imageNamed:@"apply_logo"]];
    [applyView addSubview:applyImage];
    UILabel *applyLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 40, 60, 20)];
    applyLabel.text=@"报名";
    applyLabel.textColor=[UIColor colorWithRed:0.200 green:0.200 blue:0.200 alpha:1.00];
    applyLabel.textAlignment=NSTextAlignmentCenter;
    applyLabel.font=[UIFont systemFontOfSize:10];
    [applyView addSubview:applyLabel];
    applyView.userInteractionEnabled=YES;
    UITapGestureRecognizer *applyTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(applyView:)];
    [applyView addGestureRecognizer:applyTap];
    
    deleView=[[UIView alloc] initWithFrame:CGRectMake((kScreenWidth/2.0-60)/2.0, CGRectGetMaxY(self.timeLabel.frame)+10,60, 60)];
    deleView.hidden=YES;
    [bgView addSubview:deleView];
    UIImageView *deleImage=[[UIImageView alloc] initWithFrame:CGRectMake(15, 0, 30, 30)];
    [deleImage setImage:[UIImage imageNamed:@"apply_logo"]];
    [deleView addSubview:deleImage];
    UILabel *deleLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 40, 60, 20)];
    deleLabel.text=@"撤销";
    deleLabel.textColor=[UIColor colorWithRed:0.200 green:0.200 blue:0.200 alpha:1.00];
    deleLabel.textAlignment=NSTextAlignmentCenter;
    deleLabel.font=[UIFont systemFontOfSize:10];
    [deleView addSubview:deleLabel];
    deleView.userInteractionEnabled=YES;
    UITapGestureRecognizer *deleTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(deleView:)];
    [deleView addGestureRecognizer:deleTap];
    
    UIView *questionView=[[UIView alloc] initWithFrame:CGRectMake(kScreenWidth/2.0+(kScreenWidth/2.0-60)/2.0, CGRectGetMaxY(self.timeLabel.frame)+10,60, 60)];
    [bgView addSubview:questionView];
    UIImageView *questionImage=[[UIImageView alloc] initWithFrame:CGRectMake(15, 0, 30, 30)];
    [questionImage setImage:[UIImage imageNamed:@"consultbutton_logo"]];
    [questionView addSubview:questionImage];
    UILabel *questionLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 40, 60, 20)];
    questionLabel.text=@"咨询";
    questionLabel.textColor=[UIColor colorWithRed:0.200 green:0.200 blue:0.200 alpha:1.00];
    questionLabel.textAlignment=NSTextAlignmentCenter;
    questionLabel.font=[UIFont systemFontOfSize:10];
    [questionView addSubview:questionLabel];
    questionView.userInteractionEnabled=YES;
    UITapGestureRecognizer *questionTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(questionView:)];
    [questionView addGestureRecognizer:questionTap];
    
}


- (UIImageView *)leftIcon {
    if (_leftIcon == nil) {
        UIImageView *leftBtn = [[UIImageView alloc] init];
        leftBtn.width = 15;
        leftBtn.height = 25.0;
        leftBtn.x = -3;
        leftBtn.y = 0;
        leftBtn.userInteractionEnabled = YES;
        _leftIcon = leftBtn;
    }
    return _leftIcon;
}

-(void)initWithData{
    if (kScreenHeight<=568) {
        _ImageSize=70;
        _ImageAllSize=80;
    }else if (kScreenHeight<736&&kScreenHeight>568){
        _ImageSize=82;
        _ImageAllSize=90;
    }else{
        _ImageSize=93;
        _ImageAllSize=100;
    }

}


#pragma mark ----加载网络数据
- (void)loadData {
    _messageArray=[[NSMutableArray alloc] initWithCapacity:0];
    [MBManager showLoading];
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBJSONRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@%@",MESSAGE_DETAIL,_MessageID];
        request.methodType = ZBMethodTypeGET;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        //        [MBManager hideAlert];
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"消息详情%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            [MBManager hideAlert];
            NSDictionary *value=[dataDict objectForKey:@"value"];
            _titleLabel.text=[value objectForKey: @"message_title"];
            _senderLabel.text=[NSString stringWithFormat:@"发送人：%@",[value objectForKey:@"sender_username"]];
            _contentLabel.text=[value objectForKey:@"message_content"];
            _timeLabel.text=[value objectForKey:@"send_time"];
            NSString *message_images=[value objectForKey:@"message_images"];
            [_messageImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMG_OSS,message_images]]];
            _messageArray=[value objectForKey:@"child"];
            [self.tableView reloadData];
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSError *error) {
        
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
        
        }
    }];
}

-(void)leftBtnDidClick{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)viewWillAppear:(BOOL)animated{
    
    [self loadData];
    
}

#pragma mark 报名
-(void)applyView:(UITapGestureRecognizer *)tap{
    [MBManager showLoading];
    self.applymanager=[MAToolUtils getHttpRequestUserInfoWithURL];
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    NSMutableDictionary *parmars=[[NSMutableDictionary  alloc] init];
    [parmars setObject:userinfo.cuserid forKey:@"userkey"];
    [parmars setObject:_MessageID forKey:@"msgkey"];
    NSString *url=[NSString stringWithFormat:@"%@%@",MESSAGE_SIGN,_MessageID];
    [self.applymanager.requestSerializer setValue:userinfo.token forHTTPHeaderField:@"token"];
    [self.applymanager POST:url parameters:parmars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            [MBManager hideAlert];
            applyView.hidden=YES;
            deleView.hidden=NO;
            [Toast showWithText:@"报名成功" duration:1];
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBManager hideAlert];
    }];
}

#pragma mark 撤销报名
-(void)deleView:(UITapGestureRecognizer *)tap{
    [MBManager showLoading];
    self.delemanager=[MAToolUtils getHttpRequestUserInfoWithURL];
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    NSMutableDictionary *parmars=[[NSMutableDictionary  alloc] init];
    [parmars setObject:userinfo.cuserid forKey:@"userkey"];
    [parmars setObject:_MessageID forKey:@"msgkey"];
    NSString *url=[NSString stringWithFormat:@"%@%@",MESSAGE_DELETE_SIGN,_MessageID];
    [self.delemanager.requestSerializer setValue:userinfo.token forHTTPHeaderField:@"token"];
    [self.delemanager POST:url parameters:parmars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            [MBManager hideAlert];
            applyView.hidden=NO;
            deleView.hidden=YES;
            [Toast showWithText:@"撤销报名成功" duration:1];
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        [MBManager hideAlert];
    }];
    
}

#pragma mark 咨询
-(void)questionView:(UITapGestureRecognizer *)tap{
    MAEnteringVC *vc=[[MAEnteringVC alloc] init];
    vc.messageID=_MessageID;
    vc.sender_key=_sender_key;
    vc.message_typechild=_message_typechild;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark UITableView Delegate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _messageArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height=106;
    CGFloat collect_height=0;
    NSDictionary *dic=[_messageArray objectAtIndex:indexPath.row];
    //内容的高
    CGFloat message_height=0;
    NSString *message_content;
    if ([[dic objectForKey:@"message_content"] isEqual:[NSNull null]]) {
        message_content=@"";
        message_height=0;
    }else{
        message_content=[dic objectForKey:@"message_content"];
        message_height=[MAToolUtils getNSStringHeight:message_content andFont:[UIFont systemFontOfSize:14] andTextWidth:(kScreenWidth-24)];
         height+=message_height+20;
    }
    //图片的高
    NSString *message_images=[dic objectForKey:@"message_images"];
    NSArray *message_imagesArr;
    if ([message_images isEqual:[NSNull null]]) {
        message_imagesArr=[NSArray new];
    }else{
        message_imagesArr=[message_images componentsSeparatedByString:@","];
    }
    if(message_imagesArr.count<=3&&message_imagesArr.count>0) {
        collect_height=_ImageAllSize;
    }else if (message_imagesArr.count>3&&message_imagesArr.count<=6){
        collect_height=_ImageAllSize*2;
    }else if(message_imagesArr.count>6){
        collect_height=_ImageAllSize*3;
    }else{
        collect_height=0;
    }
    height+=collect_height;
    
    return height;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellID=[NSString stringWithFormat:@"MessageCellID%ld",indexPath.row];
    MAMessageDetailCell *cell= [tableView cellForRowAtIndexPath:indexPath];
    NSDictionary *dic;
    if (_messageArray.count>0) {
        dic=[_messageArray objectAtIndex:indexPath.row];
    }
    NSString *message_images=[dic objectForKey:@"message_images"];
    NSArray *message_imagesArr;
    if ([message_images isEqual:[NSNull null]]) {
        message_imagesArr=[NSArray new];
    }else{
       message_imagesArr=[message_images componentsSeparatedByString:@","];
    }
    if (cell==nil) {
        cell=[[MAMessageDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        if (message_imagesArr.count>0) {
            for (int i=0; i<message_imagesArr.count; i++) {
                UIImageView* imageView=[[UIImageView alloc] init];
                imageView.tag=600+i;
                [cell.imageViewBg addSubview:imageView];
            }
        }
    }
    cell.backgroundColor=[UIColor colorWithRed:0.922 green:0.922 blue:0.922 alpha:1.00];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    NSString *sender_username=[dic objectForKey:@"sender_username"];
    if ([sender_username isKindOfClass:[NSNull class]]) {
         cell.nameLabel.text=@"";
    }else{
         cell.nameLabel.text=sender_username;
    }
    NSString *reciever_name=[dic objectForKey:@"reciever_name"];
    if ([reciever_name isKindOfClass:[NSNull class]]) {
        cell.roleLabel.text=@"";
    }else{
        cell.roleLabel.text=reciever_name;
    }
    NSString *sender_img=[dic objectForKey:@"sender_img"];
    //头像
    if (![sender_img isKindOfClass:[NSNull class]]) {
      [cell.photoImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMG_OSS,sender_img]]];
    }else{
         [cell.photoImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",IMG_OSS]]];
    }
    //内容
    NSString *message_content;
    if ([[dic objectForKey:@"message_content"] isEqual:[NSNull null]]) {
        cell.contentLabel.text=@"";
    }else{
        message_content=[dic objectForKey:@"message_content"];
         cell.contentLabel.text=message_content;
    }
     CGFloat message_height=[MAToolUtils getNSStringHeight:message_content andFont:[UIFont systemFontOfSize:14] andTextWidth:(kScreenWidth-24)];
    cell.contentLabel.frame=CGRectMake(6, CGRectGetMaxY(cell.roleLabel.frame)+10, cell.bgView.frame.size.width-12, message_height);
    //图片
    CGFloat collect_height=0;
    if(message_imagesArr.count<=3&&message_imagesArr.count>0) {
        collect_height=_ImageAllSize;
    }else if (message_imagesArr.count>3&&message_imagesArr.count<=6){
        collect_height=_ImageAllSize*2;
    }else if(message_imagesArr.count>6){
        collect_height=_ImageAllSize*3;
    }else{
        collect_height=0;
        cell.imageViewBg.hidden=YES;
    }
    if (message_content.length==0) {
        cell.imageViewBg.frame=CGRectMake(6, CGRectGetMaxY(cell.roleLabel.frame)+10,kScreenWidth-12,collect_height);
    }else{
        cell.imageViewBg.frame=CGRectMake(6, CGRectGetMaxY(cell.contentLabel.frame)+10,kScreenWidth-12,collect_height);
    }
    if (message_imagesArr.count>0) {
        for (int i=0; i<message_imagesArr.count; i++) {
            UIImageView* imageView=[cell.imageViewBg viewWithTag:600+i];
            [imageView setContentMode:UIViewContentModeScaleAspectFill];
            imageView.clipsToBounds = YES;
            NSInteger index = i % 3;
            NSInteger page = i / 3;
            imageView.frame=CGRectMake(0+(_ImageSize+3)*index,page*(_ImageSize+3), _ImageSize, _ImageSize);
            [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMG_OSS,[message_imagesArr objectAtIndex:i]]]];
        }
    }
    //时间
    cell.timeLabel.frame=CGRectMake(6, CGRectGetMaxY(cell.imageViewBg.frame)+10, kScreenWidth-12, 20);
    NSString *time=[dic objectForKey:@"send_time"];
    if ([time isKindOfClass:[NSNull class]]||[time isEqualToString:@"<null>"]) {
        cell.timeLabel.text=@"";
    }else{
        cell.timeLabel.text=time;
    }
   
    cell.deleBtn.tag=indexPath.row;
    [cell.deleBtn addTarget:self action:@selector(deleMessage:) forControlEvents:UIControlEventTouchUpInside];
    
    cell.bgView.frame=CGRectMake(6, 6, kScreenWidth-12,CGRectGetMaxY(cell.timeLabel.frame)+10);
    return cell;
}

#pragma mark 删除消息
-(void)deleMessage:(UIButton *)b{
    [MBManager showLoading];
    NSDictionary *dict=[_messageArray objectAtIndex:b.tag];
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request) {
        request.requestSerializerType = ZBJSONRequestSerializer;
        request.URLString = [NSString stringWithFormat:@"%@%@",DETAIL_MESSAGE_DELETE,[dict objectForKey:@"keyid"]];
        request.methodType = ZBMethodTypePOST;
        [request setValue:userinfo.token forHeaderField:@"token"];
        request.apiType = ZBRequestTypeRefresh;
    } success:^(id responseObject, apiType type) {
        //        [MBManager hideAlert];
        // 解析数据
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        DLog(@"消息详情%@",dataDict);
        NSInteger code = [dataDict[@"msgcode"] integerValue];
        if (code == 1) { // 请求成功
            [MBManager hideAlert];
            [self loadData];
        } else {
            [MBManager showBriefAlert:dataDict[@"message"]];
        }
    } failure:^(NSError *error) {
        DLog(@"%@",error);
        
    } finished:^(id responseObject, apiType type, NSError *error, BOOL isCache) {
        if (isCache==YES) {
            DLog(@"使用了缓存");
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
